package com.time.workshop.ui;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.time.workshop.API;
import com.time.workshop.App;
import com.time.workshop.BaseConstant;
import com.time.workshop.R;
import com.time.workshop.SuperActivity;
import com.time.workshop.bean.BaseResponse;
import com.time.workshop.bean.RequestOrder;
import com.time.workshop.bean.ResponseOrder;
import com.time.workshop.bean.UserInfo;
import com.time.workshop.injector.Injector;
import com.time.workshop.injector.V;
import com.time.workshop.utils.CommonUtils;
import com.time.workshop.utils.Log;
import com.time.workshop.utils.NewToast;
import com.time.workshop.utils.PreferenceUtil;

/**
 * 订单
 * 
 * @author wangfeng
 * 
 */
public class ConfirmOrderActivity extends SuperActivity implements OnClickListener
{
	@V
	private ImageView img_login_back;
	@V
	private RelativeLayout content_Layout, remarks_Layout, address_Layout, mealtime_Layout, mealcount_Layout, price_Layout;
	@V
	private TextView advanceTextView, pay_commit, priceTextView, mealtimeTextView, mealcountTextView, contentTextView, nameTextView, phoneTextView, addressTextView, remarksTextView, pay_price, tv_address;
	@V
	private View mealtimeview, mealcountview, addressview;
	private String name, content, phone, address, laorenType, price, time, store_id, number, idnumber;

	/** 返回数据总体的实体类 */
	private class Response extends BaseResponse<UserInfo>
	{
	};

	private Response mUserInfo;

	@Override
	protected void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_confirm_order);

		// String orderCode = getIntent().getExtras().getString("orderCode");
		// System.out.println("orderCode::"+orderCode);
		init();
		intent();
	}

	private void init()
	{
		Injector.getInstance().inject(this);
		img_login_back.setOnClickListener(this);
		pay_commit.setOnClickListener(this);
		setView(App.getInstance().type);
	}

	private void intent()
	{
		Intent in = getIntent();
		if (App.getInstance().type == BaseConstant.TONGCHENG || App.getInstance().type == BaseConstant.PEIPAO || App.getInstance().type == BaseConstant.CHONGWU || App.getInstance().type == BaseConstant.XUYUAN)
		{
			name = in.getStringExtra("name");
			content = in.getStringExtra("content");
			phone = in.getStringExtra("phone");
			nameTextView.setText(name);
			phoneTextView.setText(phone);
			contentTextView.setText(content);
		} else if (App.getInstance().type == BaseConstant.LAOREN)
		{
			name = in.getStringExtra("name");
			content = in.getStringExtra("content");
			phone = in.getStringExtra("phone");
			address = in.getStringExtra("address");
			laorenType = in.getStringExtra("type");
			nameTextView.setText(name);
			phoneTextView.setText(phone);
			contentTextView.setText(content);
			addressTextView.setText(address);
		} else if (App.getInstance().type == BaseConstant.WAIMAI)
		{
			name = in.getStringExtra("name");
			content = in.getStringExtra("remark");
			phone = in.getStringExtra("phone");
			address = in.getStringExtra("address");
			price = in.getStringExtra("price");
			time = in.getStringExtra("waimaitime");
			store_id = in.getStringExtra("store_id");
			nameTextView.setText(name);
			remarksTextView.setText(content);
			phoneTextView.setText(phone);
			addressTextView.setText(address);
			priceTextView.setText(price);
			mealtimeTextView.setText(time);
			pay_price.setVisibility(View.VISIBLE);
			pay_price.setText("合计:" + price + "元");
		} else if (App.getInstance().type == BaseConstant.DINGZUO || App.getInstance().type == BaseConstant.GUAHAO)
		{
			price = in.getStringExtra("price");
			priceTextView.setText(price);
			time = in.getStringExtra("dingzuotime");
			mealtimeTextView.setText(time);
			number = in.getStringExtra("dingzuomun");
			mealcountTextView.setText(number);
			name = in.getStringExtra("name");
			nameTextView.setText(name);
			phone = in.getStringExtra("phone");
			phoneTextView.setText(phone);
			content = in.getStringExtra("remark");
			store_id = in.getStringExtra("store_id");
			if (App.getInstance().type == BaseConstant.DINGZUO)
			{
				remarksTextView.setText(content);
			} else
			{
				contentTextView.setText(content);
			}
			pay_price.setVisibility(View.VISIBLE);
			pay_price.setText("合计:" + Integer.valueOf(price) * Integer.valueOf(number) + "元");
		} else if (App.getInstance().type == BaseConstant.BUYTIME)
		{
			idnumber = in.getStringExtra("idnumber");
			addressTextView.setText(idnumber);
			name = in.getStringExtra("name");
			nameTextView.setText(name);
			phone = in.getStringExtra("phone");
			phoneTextView.setText(phone);
			content = in.getStringExtra("content");
			contentTextView.setText(content);
		}
	}

	private void setView(int type)
	{
		if (type == BaseConstant.DINGZUO)
		{// 订座
			remarks_Layout.setVisibility(View.VISIBLE);
			mealcount_Layout.setVisibility(View.VISIBLE);
			mealtime_Layout.setVisibility(View.VISIBLE);
			mealcountview.setVisibility(View.VISIBLE);
			mealtimeview.setVisibility(View.VISIBLE);
		} else if (type == BaseConstant.WAIMAI)
		{// 外卖
			remarks_Layout.setVisibility(View.VISIBLE);
			mealcount_Layout.setVisibility(View.VISIBLE);
			address_Layout.setVisibility(View.VISIBLE);
			mealcountview.setVisibility(View.VISIBLE);
			addressview.setVisibility(View.VISIBLE);
		} else if (type == BaseConstant.TONGCHENG)
		{// 同城
			price_Layout.setVisibility(View.GONE);
			content_Layout.setVisibility(View.VISIBLE);
			advanceTextView.setText(getResources().getString(R.string.custommade));
		} else if (type == BaseConstant.GUAHAO)
		{// 挂号
			content_Layout.setVisibility(View.VISIBLE);
			advanceTextView.setText(getResources().getString(R.string.confirm_guahao));
		} else if (type == BaseConstant.LAOREN)
		{// 老人专区
			price_Layout.setVisibility(View.GONE);
			content_Layout.setVisibility(View.VISIBLE);
			address_Layout.setVisibility(View.VISIBLE);
			addressview.setVisibility(View.VISIBLE);
			advanceTextView.setText(getResources().getString(R.string.laoren));
		} else if (type == BaseConstant.CHONGWU || type == BaseConstant.PEIPAO || type == BaseConstant.XUYUAN)
		{// 宠物、陪跑、许愿
			price_Layout.setVisibility(View.GONE);
			content_Layout.setVisibility(View.VISIBLE);
			advanceTextView.setText(getResources().getString(R.string.chongwu));
		} else if (type == BaseConstant.BUYTIME)
		{
			price_Layout.setVisibility(View.GONE);
			content_Layout.setVisibility(View.VISIBLE);
			address_Layout.setVisibility(View.VISIBLE);
			addressview.setVisibility(View.VISIBLE);
			advanceTextView.setText(getResources().getString(R.string.buytime));
			tv_address.setText("身份证号");
		}
	}

	private RequestOrder requestOrder;

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.img_login_back:
			CommonUtils.hide(this);
			back();
			break;
		case R.id.pay_commit:
			requestOrder = new RequestOrder();
			showLoadingDialog();
			requestOrder.contactor_person = nameTextView.getText().toString().trim();
			requestOrder.contactor_phone = phoneTextView.getText().toString().trim();
			requestOrder = getType(requestOrder);
			submitOrder(requestOrder, ConfirmOrderActivity.this);
			break;
		default:
			break;
		}
	}

	private RequestOrder getType(RequestOrder order)
	{
		int type = App.getInstance().type;
		if (type == BaseConstant.DINGZUO)
		{// 订座
			order.reservation_person = mealcountTextView.getText().toString().trim();
			order.reservation_time = mealtimeTextView.getText().toString().trim();
			order.remark = remarksTextView.getText().toString().trim();
			order.ORDER_TYPE = "YDDD";
			order.store_id = store_id;
		} else if (type == BaseConstant.WAIMAI)
		{// 外卖
			order.reservation_time = mealtimeTextView.getText().toString().trim();
			order.contactor_address = addressTextView.getText().toString().trim();
			order.remark = remarksTextView.getText().toString().trim();
			order.price = priceTextView.getText().toString().trim();
			order.ORDER_TYPE = "WMDD";
			order.store_id = store_id;
		} else if (type == BaseConstant.TONGCHENG)
		{// 同城
			order.remark = contentTextView.getText().toString().trim();
			order.ORDER_TYPE = "TCDD";
		} else if (type == BaseConstant.GUAHAO)
		{// 挂号
			order.remark = contentTextView.getText().toString().trim();
			order.ORDER_TYPE = "GHDD";
			order.store_id = store_id;
		} else if (type == BaseConstant.LAOREN)
		{// 老人专区
			order.ORDER_TYPE = laorenType;
			order.remark = contentTextView.getText().toString().trim();
			order.contactor_address = addressTextView.getText().toString().trim();
		} else if (type == BaseConstant.CHONGWU)
		{// 宠物
			order.remark = contentTextView.getText().toString().trim();
			order.ORDER_TYPE = "LCWDD";
		} else if (type == BaseConstant.PEIPAO)
		{// 、陪跑
			order.remark = contentTextView.getText().toString().trim();
			order.ORDER_TYPE = "PPDD";
		} else if (type == BaseConstant.XUYUAN)
		{
			order.remark = contentTextView.getText().toString().trim();
			order.ORDER_TYPE = "XYHZ";
		} else if (type == BaseConstant.BUYTIME)
		{
			order.ID_CARD = addressTextView.getText().toString().trim();
			order.ORDER_TYPE = "SJGF";
		}
		return order;

	}

	/**
	 * 提交订单
	 * 
	 * @param orderBean
	 * @param context
	 */
	public void submitOrder(RequestOrder orderBean, final Activity context)
	{
		if ("".equals(CommonUtils.isNull(PreferenceUtil.getString(getApplicationContext(), BaseConstant.PREF_TOKE_STRING))) || "".equals(CommonUtils.isNull(PreferenceUtil.getString(getApplicationContext(), BaseConstant.PREF_USERNAME_STRING))) || "".equals(CommonUtils.isNull(PreferenceUtil.getString(getApplicationContext(), BaseConstant.PREF_PASSWORD_STRING))))
		{
			Intent in = new Intent(ConfirmOrderActivity.this, LoginActivity.class);
			startActivity(in, true);
			return;
		}
		if (!CommonUtils.isNetworkConnected(getApplicationContext()))
		{
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}
		RequestParams param = new RequestParams();
		param.addBodyParameter("ORDER_TYPE", orderBean.ORDER_TYPE);
		param.addBodyParameter("remark", orderBean.remark);
		param.addBodyParameter("contactor_person", orderBean.contactor_person);
		param.addBodyParameter("contactor_phone", orderBean.contactor_phone);
		param.addBodyParameter("contactor_address", orderBean.contactor_address);
		param.addBodyParameter("reservation_person", orderBean.reservation_person);
		param.addBodyParameter("reservation_time", orderBean.reservation_time);
		param.addBodyParameter("store_id", orderBean.store_id);
		param.addBodyParameter("ID_CARD", orderBean.ID_CARD);
		param.addBodyParameter("token", PreferenceUtil.getString(context, BaseConstant.PREF_TOKE_STRING));
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.POST, API.submitOrder, param, new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{
				super.onStart();
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				Log.d("onSuccess==", responseInfo + "");
				dismissLoadingDialog();
				try
				{
					Gson gson = new Gson();
					ResponseOrder responseOrder = gson.fromJson(responseInfo.result, ResponseOrder.class);
					Log.d("responseOrder==", responseOrder.toString());
					if (responseOrder.success)
					{
						NewToast.makeText(context, responseOrder.message);
						Intent in = new Intent(ConfirmOrderActivity.this, OrderDetailActivity.class);
						in.putExtra("orderId", responseOrder.result.getID());
						startActivity(in, true);
						finish();
					} else
					{
						NewToast.makeText(context, responseOrder.message);
						if (1 == responseOrder.resCode)
						{
							doLoginRequest(PreferenceUtil.getString(getApplicationContext(), BaseConstant.PREF_USERNAME_STRING), PreferenceUtil.getString(getApplicationContext(), BaseConstant.PREF_PASSWORD_STRING));
						}
					}
				} catch (Exception e)
				{
					e.printStackTrace();
					NewToast.makeText(context, e.getMessage());
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{
				Log.d("onFailure==", msg + "");
				NewToast.makeText(context, "fail" + msg);
				dismissLoadingDialog();
			}
		});
	}

	/** token过期后再次登录 */
	private void doLoginRequest(String pho, final String pwd)
	{
		showDialog(null);
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("username", pho);
		params.addQueryStringParameter("password", pwd);

		HttpUtils httpUtils = new HttpUtils();

		httpUtils.send(HttpMethod.GET, API.login, params, new RequestCallBack<String>()
		{

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				Log.d("onSuccess==", responseInfo.result + "");

				dismissLoadingDialog();
				try
				{
					JSONObject jsonObject = new JSONObject(responseInfo.result);
					Gson gson = new Gson();

					mUserInfo = gson.fromJson(jsonObject.toString(), Response.class);

					Log.d("mUserInfo", mUserInfo.getResult() + "");

					if (mUserInfo.isSuccess())
					{

						// 保存登录返回的Token
						PreferenceUtil.putString(ConfirmOrderActivity.this, BaseConstant.PREF_TOKE_STRING, mUserInfo.getResult().getTOKEN() + "");
						submitOrder(requestOrder, ConfirmOrderActivity.this);
					} else
					{
						NewToast.makeText(getApplicationContext(), mUserInfo.getMessage());
					}
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{
				dismissLoadingDialog();
				Log.d("onFailure==", msg + "");
				NewToast.makeText(getApplicationContext(), R.string.login_failure);
			}

		});
	}
}
